package org.geektimes.projects.user.oauth2;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* open authentication委托器  
* @author : lsq
*/
public class OAuth2ConfigurationDelegate implements OAuth2Configuration {


	public static final String ORIGIN_NAME = "originName";

	public static final String RESPONSE_TYPE = "code";
	/**
	 * 配置列表
	 */
	private List<OAuth2Configuration> auth2Configurations = new ArrayList<>();

	/**
	 * 配置映射 originName - > config
	 */
	private Map<String , OAuth2Configuration>  configurationMap = new HashMap<>();
	/**
	 * 当前授权码
	 */
	private ThreadLocal<String> code = new ThreadLocal<>();
	/**
	 * 当前配置
	 */
	private ThreadLocal<OAuth2Configuration> currentConfig = new ThreadLocal<>();

	public  void addConfiguration(OAuth2Configuration oAuth2Configuration){
		this.auth2Configurations.add(oAuth2Configuration);
	}

	/**
	 * 初始化
	 */
	public void init(){
		auth2Configurations.forEach(config -> {
			configurationMap.putIfAbsent(config.getOriginName() , config);
		});
	}

	/**
	 * 准备配置
	 * @param httpServletRequest
	 */
	public void preConfig(HttpServletRequest httpServletRequest){
		//获取来源名称
		String originName = httpServletRequest.getParameter(ORIGIN_NAME);
		OAuth2Configuration oAuth2Configuration = configurationMap.get(originName);
		if (oAuth2Configuration == null){
			throw new OAuth2Exception(originName , "未找到对应的第三方oauth2授权配置");
		}
		DefaultOAuth2Configuration.ParamConfiguration paramConfiguration = oAuth2Configuration.getParamConfiguration();
		if (paramConfiguration == null){
			throw new OAuth2Exception(originName , "第三方oauth2授权的参数配置不能为空");
		}
		currentConfig.set(oAuth2Configuration);
		code.set(httpServletRequest.getParameter(RESPONSE_TYPE));
	}

	@Override
	public String getOriginName() {
		return currentConfig.get().getOriginName();
	}

	@Override
	public String getAuthorizeUrl() {
		return currentConfig.get().getAuthorizeUrl();
	}

	@Override
	public String getAccessTokenUrl() {
		return currentConfig.get().getAccessTokenUrl();
	}

	@Override
	public String getJwksUrl() {
		return currentConfig.get().getJwksUrl();
	}

	@Override
	public String getClientId() {
		return currentConfig.get().getClientId();
	}

	@Override
	public String getClientSecret() {
		return currentConfig.get().getClientSecret();
	}

	@Override
	public String getCallSucceedUrl() {
		return currentConfig.get().getCallSucceedUrl();
	}

	@Override
	public String getCallFailureUrl() {
		return currentConfig.get().getCallFailureUrl();
	}

	@Override
	public String getScope() {
		return currentConfig.get().getScope();
	}


	@Override
	public DefaultOAuth2Configuration.ParamConfiguration getParamConfiguration() {
		return currentConfig.get().getParamConfiguration();
	}


	public String getAuthCode(){
		return code.get();
	}

	/**
	 * 关闭配置
	 */
	public void close(){
		this.currentConfig.remove();
		this.code.remove();
	}
}
